Skip to content

fix(datalayer): schedule count on monotonic clock - #1418

Draft
ithinkihaveacat wants to merge 1 commit into
android:mainfrom
ithinkihaveacat:fix/datalayer-monotonic-count-schedule
Draft

ithinkihaveacat wants to merge 1 commit into
android:mainfrom
ithinkihaveacat:fix/datalayer-monotonic-count-schedule

Conversation

@ithinkihaveacat

Copy link
Copy Markdown
Contributor

Summary

DataLayer's phone MainActivity sends a demonstration /count DataItem
every 5 seconds while in the RESUMED lifecycle state. Although the existing
loop attempts to subtract sendCount(count) execution time from each sleep
interval, it anchors its schedule to Instant.now() and resets that anchor
after delay(...) returns. As a result, the schedule accumulates every
coroutine/main-thread wakeup overshoot (O(N) phase drift) and can stall or
fire early whenever the system wall clock changes.

This PR switches the /count trigger schedule to Android's monotonic
SystemClock.elapsedRealtime() clock on a fixed 5-second grid, skips
already-elapsed slots after multi-interval stalls so slow calls never trigger a
catch-up burst, clarifies in comments that periodic DataClient ticks are
purely for sample traffic generation, and adds unit tests covering the
scheduling invariants.

Problem

In
DataLayer/Application/src/main/java/com/example/android/wearable/datalayer/MainActivity.kt,
the RESUMED loop previously scheduled /count updates as follows:

var lastTriggerTime = Instant.now() - (countInterval - Duration.ofSeconds(1))
while (isActive) {
    delay(
        Duration
            .between(Instant.now(), lastTriggerTime + countInterval)
            .toMillis()
    )
    lastTriggerTime = Instant.now()
    sendCount(count)
    count++
}

This has two timing bugs:

Cumulative wakeup-overshoot drift (O(N) phase drift)

Computing Duration.between(Instant.now(), lastTriggerTime + countInterval) at
the top of the loop subtracts the time spent inside sendCount(count)
(dataClient.putDataItem(...).await()). However, overwriting
lastTriggerTime = Instant.now() after delay(...) returns anchors the next
deadline to the actual wakeup instant rather than the scheduled deadline.

On Android, delay(...) on Dispatchers.Main dispatches via the main looper
and wakes after at least the requested duration plus scheduling and frame/IPC
dispatch latency (delta_i >= 0). Because each positive overshoot delta_i is
written into lastTriggerTime, every subsequent tick shifts later permanently
(t_k = t_0 + 1,000 ms + k * 5,000 ms + sum(delta_0..delta_k)):

Iteration Nominal deadline Actual wakeup (+delta_i) sendCount completion Next delay(...) (old) Next target (old)
0 1,000 ms 1,008 ms (+8 ms) 1,048 ms (40 ms IPC) 6,008 - 1,048 = 4,960 ms 6,008 ms (+8 ms drift)
1 6,000 ms 6,020 ms (+12 ms) 6,055 ms (35 ms IPC) 11,020 - 6,055 = 4,965 ms 11,020 ms (+20 ms drift)
k 1,000 + 5,000k ms Drifts monotonically Absorbed Never recovers lost phase +sum(delta_i)

Mutable wall-clock (CLOCK_REALTIME) anchoring

Instant.now() reads the system wall clock (CLOCK_REALTIME), which is not
monotonic and can jump forward or backward while the activity is open due to
automatic network time (NTP / carrier NITZ) corrections, timezone/clock updates,
or manual clock edits:

  • Backward wall-clock step (-Delta_t): If the system clock steps backward
    by 10 minutes (600,000 ms) between lastTriggerTime = Instant.now() and the
    next Duration.between(Instant.now(), lastTriggerTime + countInterval), the
    computed sleep duration becomes ~605,000 ms, stalling /count updates for
    the entire 10-minute backward adjustment.
  • Forward wall-clock step (+Delta_t): If the system clock jumps forward,
    Duration.between(...) becomes negative, causing delay(...) to return
    immediately and re-anchoring lastTriggerTime to the new wall-clock time.

(Instant.now().epochSecond in sendPhoto() is intentionally retained because
TIME_KEY records an event timestamp in the DataMap payload rather than
measuring an elapsed interval.)

Proposed Implementation

  • Monotonic deadline grid (MainActivity.kt): Replace Instant.now() and
    java.time.Duration interval tracking with SystemClock.elapsedRealtime()
    (CLOCK_BOOTTIME), preserving the 1-second initial delay
    (INITIAL_COUNT_DELAY_MS = 1_000L) and 5-second period
    (COUNT_INTERVAL_MS = 5_000L).
  • Drift-free, burst-safe deadline advancement
    (nextCountTriggerRealtimeMs):
    Advance nextTriggerRealtimeMs from
    previousTriggerRealtimeMs in multiples of COUNT_INTERVAL_MS via
    internal fun nextCountTriggerRealtimeMs(...), guarding delay(delayMs) with
    if (delayMs > 0L).
  • Sample guidance comment (MainActivity.kt): Add a brief note above the
    loop clarifying that periodic DataClient writes while RESUMED exist only
    to generate visible demonstration traffic, whereas production Wear OS apps
    should prefer event-driven state updates and self-ticking system surfaces
    (such as OngoingActivity StopwatchPart/TimerPart or
    TimeDifferenceComplicationText).
  • Unit tests (MainActivityCountScheduleTest.kt,
    Application/build.gradle.kts):
    Add testImplementation(libs.junit) to
    :Application and add fast JVM unit tests covering multi-iteration wakeup
    overshoots, sub-interval sendCount latency, multi-interval stalls, exact
    interval boundaries, early wakeups, and invalid interval validation.

Edge Cases and Rationale

  • Skipping missed intervals without catch-up bursts: Simply advancing
    nextTriggerRealtimeMs += COUNT_INTERVAL_MS eliminates wakeup drift during
    normal operation, but leaves nextTriggerRealtimeMs in the past if a slow
    putDataItem(...).await() call, debugger pause, or main-thread stall ever
    exceeds 5,000 ms. For example, if nextTriggerRealtimeMs is 1,000 ms and
    sendCount(0) stalls and completes at 13,006 ms (or delay() wakes at
    13,006 ms after a main-looper stall), a naive +5,000 ms increment would
    set the next deadline to 6,000 ms (< 13,006 ms) and emit back-to-back
    urgent DataItem writes until catching up. Computing
    missedIntervals = maxOf(0L, nowRealtimeMs - previousTriggerRealtimeMs) / intervalMs
    after sendCount(count) completes and returning
    previousTriggerRealtimeMs + (missedIntervals + 1L) * intervalMs skips the
    elapsed 6,000 ms and 11,000 ms slots and schedules the next update at
    16,000 ms (2,994 ms later), preserving grid alignment with zero burst
    traffic.
  • Exact interval boundaries and early wakeups: If nowRealtimeMs lands on
    an exact multiple of COUNT_INTERVAL_MS (now = 6,000 ms for
    previous = 1,000 ms), missedIntervals evaluates to 1 and returns
    11,000 ms (strictly in the future) rather than 6,000 ms. If timer rounding
    ever wakes slightly early (now < previous), maxOf(0L, ...) clamps
    missedIntervals to 0 and advances by a single interval (6,000 ms).
  • Lifecycle pause and resume behavior: Because nextTriggerRealtimeMs is
    scoped inside lifecycle.repeatOnLifecycle(Lifecycle.State.RESUMED) while
    var count = 0 remains scoped to onCreate, pausing the activity cancels the
    loop cleanly and resuming starts a fresh 1-second initial delay without
    resetting count across pause/resume cycles.

Verification

From DataLayer/:

  1. Run formatting, lint, and unit tests across both :Application and
    :Wearable:
    ./gradlew spotlessCheck check --stacktrace
  2. Assemble debug and minified release APKs:
    ./gradlew Application:assembleDebug Wearable:assembleDebug Wearable:assembleRelease --stacktrace

Anchor MainActivity's periodic /count sender loop to monotonic
SystemClock.elapsedRealtime() on a fixed 5-second grid instead of
resetting lastTriggerTime = Instant.now() after delay() returns.

Previously, overwriting lastTriggerTime after delay() permanently
shifted subsequent deadlines later by every main-looper wakeup
overshoot (O(N) phase drift), and reading Instant.now() coupled the
sleep duration to mutable wall-clock adjustments (stalling across
backward NTP/NITZ or manual clock steps).

Advance deadlines from the prior scheduled slot via
nextCountTriggerRealtimeMs(), skipping already-elapsed intervals if a
sendCount() call or main-thread stall exceeds 5 seconds so recovery
does not emit a back-to-back catch-up burst. Document that periodic
DataClient writes are for sample demonstration traffic only, and add
JUnit 4 unit tests covering wakeup overshoots, sub-interval IPC
latency, multi-interval stalls, and exact interval boundaries.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant